package cnhy.salary.controller;

import cn.hutool.core.date.DateUtil;
import cnhy.salary.domain.*;
import cnhy.salary.service.DepartmentSvc;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ling.common.DataUtil;
import ling.common.EQueryController;
import ling.common.domain.PageSort;
import ling.common.domain.Result;
import ling.common.domain.ResultRows;
import lombok.var;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "部门班组",value = "对系统部门管理的封装")
@RestController
@RequestMapping("/salary/Department")
public class DepartmentController extends EQueryController<Department> {


    @Resource
    private ISysDeptService deptService;

    @Resource
    DepartmentSvc departmentSvc;

    @ApiOperation(value = "生成部门树形",notes = "对系统/system/user/deptTree进行过滤")
    @GetMapping("deptTreeByRoot")
    public Result<List<TreeSelect>> deptTreeByRoot() {

        var deptTree = deptService.selectDeptTreeList(new SysDept());
        var reDeptList = departmentSvc.treeSelectFilter(gotGroupRootId(), deptTree);
        if (reDeptList == null)
            return Result.ok(new ArrayList<>());
        return Result.ok(reDeptList);
    }
    @ApiOperation(value = "员工出勤统计",notes = "all部门总数，leave请假数,postTransfer待处理调岗通知,kq0正常、1迟到、2缺卡、10补卡")
    @GetMapping("statEmpl")
    public Result<Map<String,Long>> statEmpl(Long deptId, Date time) {
        if(deptId==null)
            deptId=getDeptId();
        if(time==null)
            time=new Date();
        var map = departmentSvc.statEmpl(deptId, DateUtil.beginOfDay(time),DateUtil.endOfDay(time));
        Long finalDeptId = deptId;
        var postTranCount=queryHelper.entityQuery(PostTransfer.class)
                .where(p ->p.newDept().eq(finalDeptId) )
                .where(p ->p.status().eq(1)).count();
        map.put("postTransfer",postTranCount);
        return Result.ok(map);
    }
    @ApiOperation(value = "分页列表",notes = "参数lv:2班组，3生产部门,不传则忽略")
    @GetMapping("list")
    public ResultRows<Department> list(Department dto,Integer lv, PageSort pageRequest) {
        gainPageDomain(pageRequest);
        var rootPath= gotGroupRootPath();
        var pitem = queryHelper.entityQuery(Department.class)
                .where(p -> p.delFlag().eq("0"))  // 新增条件：只查未删除数据
                .where(lv==3,p->p.parentId().eq(gotGroupRootId()))
                .where(lv==2,p->p.ancestors().like(rootPath+","))
                .whereObject(dto != null, dto);
            pitem.orderByObject( pageRequest);
        var pData = pitem.orderBy(p->p.deptId().desc()).toPageResult(pageRequest.getPageNum(), pageRequest.getPageSize());
        if(lv==2)
        {
           var pids= pData.getData().stream().map(p->p.getParentId()).distinct().collect(Collectors.toList());
            var ps=queryHelper.entityQuery(Department.class).where(p->p.deptId().in(pids)).where(p -> p.delFlag().eq("0")).toList();
            DataUtil.findSet(pData.getData(),ps
                    ,(p,p1)-> Objects.equals(p.getParentId(), p1.getDeptId())
                    ,(p, p2)->{
                p.setParentName(p2.getDeptName());
            });
        }

        return toResultRows(pData);
    }
    @ApiOperation("详情")
    @PreAuthorize("@ps.any(@pay.dailyWage.query)")
    @GetMapping(value = "/{id}")
    public Result<Department> getInfo(@PathVariable("id") Long id)
    {
        var dept = queryHelper.entityQuery(Department.class).where(d -> d.deptId().eq(id)).firstOrNull();
        return Result.ok(dept);
    }

    /**
     * 添加班组，添加
     * 主任部门
     */
    @ApiOperation(value = "新增班组,新增后为停用状态",notes = "lv3Id所属生成部门，name班组名称,lineId产线id")
    @Log(title = "部门班组", businessType = BusinessType.INSERT)
    @PostMapping("addLv2")
    public Result addLv2(@RequestBody Department dept) {

        var repeatCount = queryHelper.entityQuery(Department.class).where(d -> d.deptName().eq(dept.getDeptName())).intCount();
        if (repeatCount > 0)
            return Result.bad("名称重复");
        var parent = queryHelper.entityQuery(Department.class).where(d -> d.deptId().eq(dept.getParentId())).firstOrNull();
        if (parent == null)
            return Result.bad("父级无法找到");
        else {
            if (!Objects.equals(parent.getParentId(), gotGroupRootId()))
                return Result.bad("父级错误");
        }
        var newLv2 = new Department();
        if(dept.getLineId()!=null){
            var line=queryHelper.entityQuery(ProductionLine.class).whereById(dept.getLineId()).firstOrNull();
            if(line==null)
                return Result.bad("产线无法找到");
            newLv2.setLineId(dept.getLineId());
            newLv2.setLineName(line.getName());
        }

        newLv2.setParentId(dept.getParentId());
        newLv2.setDeptName(dept.getDeptName());
        newLv2.setCreateBy(getUsername());
        newLv2.setCreateTime(new Date());
        //newLv2.setStatus(UserConstants.DEPT_DISABLE);

        newLv2.setLeaderId(dept.getLeaderId());
        newLv2.setLeader(dept.getLeader());
        if(dept.getLeaderId()!=null) {
            var emp = queryHelper.entityQuery(Employee.class).where(e -> e.userId().eq(dept.getLeaderId())).firstOrNull();
            newLv2.setPhone(emp.getPhone());
            newLv2.setLeader(emp.getName());
        }
        departmentSvc.insertDept(newLv2);

        return Result.ok();
    }
    @ApiOperation("编辑班组")
    @Log(title = "部门班组", businessType = BusinessType.INSERT)
    @PostMapping("editLv2")
    public Result editLv2(@RequestBody Department dept) {

        var old = queryHelper.entityQuery(Department.class).whereById(dept.getDeptId()).firstOrNull();

        var leaderId = dept.getLeaderId();
        if (leaderId == null) {
            old.setLeader(null);
            old.setPhone(null);
            old.setLeaderId(null);
        } else {
            var emp = queryHelper.entityQuery(Employee.class).where(e -> e.userId().eq(leaderId)).firstOrNull();
            old.setLeader(emp.getName());
            old.setPhone(emp.getPhone());
            old.setLeaderId(emp.getUserId());
        }
        old.setStatus(dept.getStatus());
        old.setDeptName(dept.getDeptName());
        old.setLineId(dept.getLineId());
        if (old.getLeaderId() == null) {
            old.setLineName(null);
        } else {
            var line = queryHelper.entityQuery(ProductionLine.class).whereById(dept.getLineId()).firstOrNull();
            old.setLineName(line.getName());
        }
        queryHelper.entityQuery().updatable(old).executeRows();
        return Result.ok();
    }

    @ApiOperation("删除班组")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public Result remove(@PathVariable Long deptId)
    {

        if (deptService.checkDeptExistUser(deptId))
        {
            return Result.bad("部门存在用户,不允许删除");
        }
        deptService.deleteDeptById(deptId);
        return Result.ok();
    }



    @ApiOperation("新增主任部门,新增后为停用状态")
    @Log(title = "部门班组", businessType = BusinessType.INSERT)
    @PostMapping("addLv3")
    public Result addLv3(@RequestBody Department department) {
        var repeatCount = queryHelper.entityQuery(Department.class).where(d -> d.deptName().eq(department.getDeptName())).intCount();
        if (repeatCount > 0)
            return Result.bad("名称重复");

        var newLv3 = new Department();
        newLv3.setParentId(gotGroupRootId());
        newLv3.setDeptName(department.getDeptName());
        newLv3.setCreateBy(getUsername());
        newLv3.setCreateTime(new Date());
        newLv3.setStatus(UserConstants.DEPT_NORMAL);
        newLv3.setLeaderId(department.getLeaderId());
        newLv3.setLeader(department.getLeader());

        //deptService.insertDept(newLv3);
        if(department.getLeaderId()!=null) {
            var emp = queryHelper.entityQuery(Employee.class).where(e -> e.userId().eq(department.getLeaderId())).firstOrNull();
            newLv3.setPhone(emp.getPhone());
            newLv3.setLeader(emp.getName());
        }
        //queryHelper.entityQuery().insertable(newLv3).executeRows();
        departmentSvc.insertDept(newLv3);
        return Result.ok();
    }
    @ApiOperation(value = "编辑生成部门",notes = "编辑：负责人leaderId、启停用Status")
    @Log(title = "部门班组", businessType = BusinessType.INSERT)
    @PostMapping("editLv3")
    public Result editLv3(@RequestBody Department dept) {


        var old = queryHelper.entityQuery(Department.class).whereById(dept.getDeptId()).firstOrNull();

        if (!Objects.equals(old.getParentId(), gotGroupRootId()))
            return Result.bad("必须为生成部门");
        var leaderId = dept.getLeaderId();
        var emp = queryHelper.entityQuery(Employee.class).where(e -> e.userId().eq(leaderId)).firstOrNull();
        if (emp != null) {
            old.setLeader(emp.getName());
            old.setPhone(emp.getPhone());
            old.setLeaderId(emp.getUserId());
        }
        old.setStatus(dept.getStatus());
        old.setDeptName(dept.getDeptName());

        queryHelper.entityQuery().updatable(old).executeRows();
        return Result.ok();
    }

//    @Log(title = "部门班组", businessType = BusinessType.DELETE)
//    @DeleteMapping("/{ids}")
//    public Result remove(@PathVariable Long[] ids){
//
//       var re= deptService.deleteDeptById(ids[0]);
//        return  Result.ok(re);
//    }
    Long groupRootId;
    Long gotGroupRootId() {
        if (groupRootId == null) {
            groupRootId =departmentSvc.gotGroupRoot().getId();
        }
        return  groupRootId;
    }
    String groupRootPath;
    String gotGroupRootPath() {
        if (groupRootPath == null) {
           var root =departmentSvc.gotGroupRoot();
            groupRootPath =root.getAncestors()+","+root.getId();
        }
        return  groupRootPath;
    }
}
